import Cookies from 'js-cookie';
import axios from 'axios';
import { reactive } from 'vue'
import  "./env-setting";
import { publicConfig } from "./public-init";
import {TwFrontLog} from "./front-log";
import {UiUtils} from "./ui-utils";
import router from '@/management/router'

class User {
  authList = []
  /**
   * 功能：验证用户是否有在eco的应用中配置的权限
   * @param {String,Array} auth 权限菜单或列表
   * @param {Boolean} exact 是否开启精确匹配
   */
  hasAuth (auth, exact) {
    const auths = Array.isArray(auth) ? auth : [auth]
    const result = this.authList.filter(auth => auths.includes(auth.menuPath))

    if (exact) {
      return result.length === auths.length
    } else {
      return result.length > 0
    }
  }
  
}


export default {
 async install (app, options = {}) {
  
    let config = {}

    for (const key in import.meta.env) {
      if (Object.prototype.hasOwnProperty.call(import.meta.env, key)) {
        if (/^VUE_APP_/.test(key)) {
          let _key = key
            .replace(/^VUE/, '')
            .replace(/_(\w)([^_]*)/g, (m, p1, p2) => p1 + p2.toLowerCase())
            .replace(/^(\w)/, (m, p1) => p1.toLowerCase())

          config[_key] = import.meta.env[key]
        }
      }
    }

    const authorizedKey = `${window.$app.appId}_authorized`
    const userKey = `${window.$app.appId}_user`

    Object.assign(config, publicConfig, options, {
      setAuth (user, isAdditional) {
        if (typeof user === 'object') {
          let _user = new User()

          if (isAdditional) {
            _user = Object.assign(_user, JSON.parse(localStorage.getItem(userKey)) || {}, user)
          } else {
            Object.assign(_user, user)
          }

          Cookies.set(authorizedKey, true)
          window.$app.user = _user
          localStorage.setItem(userKey, JSON.stringify(_user))
          // 加个sessionStorage存储处理c15跳转的 重构c17删掉
          localStorage.setItem('userInfo', JSON.stringify(_user))
          if (_user.teachInfo) {
            localStorage.setItem('teachInfo', JSON.stringify(_user.teachInfo))
          }
          // 加个sessionStorage存储处理c15跳转的 重构c17删掉
        }
      },

      delAuth (gotoLoginPage, joinUrl = '') {
        console.log('delAuth', gotoLoginPage)
        function handleLogoOut () {
          if (gotoLoginPage) {
            if (window?.__POWERED_BY_WUJIE__) { // 丛课堂来，则直接返回课堂登录
              window?.parent?.$app?.delAuth(true)
              return
            }
            if (window?.$app?.appType === 'pc' || window?.CefSharp) {
              window.$twpc.basic.logOut.send()
            } else if (window?.$app?.appType === 'web') {
              let handleHashChange = function () {
                window.removeEventListener('hashchange', handleHashChange)
                window.location.reload()
              }

              window.addEventListener('hashchange', handleHashChange)

              let next = (window.$app.exitLoginPage || options.loginPage || window.$app.loginPage) + joinUrl
              window.top.location.href = next
            } else if (window?.$app?.appType === 'pad') {
              window.$ui.backToPadXBLLogin()
            } else if (window?.__wxjs_environment === 'miniprogram') {
              // const wx = require('weixin-js-sdk')
              // wx.miniProgram.switchTab({ url: '/pages/homePage/index' })
            } else if (window?.$native) {
              window.$native.back.send()
            } else {
              
              let handleHashChange = function () {
                window.removeEventListener('hashchange', handleHashChange)
                window.location.reload()
              }

              window.addEventListener('hashchange', handleHashChange)

              if (joinUrl) {
                let next = (window.$app.exitLoginPage || options.loginPage || window.$app.loginPage) + joinUrl
                window.location.href = next
              } else {
                router.push('/login')
              }
            }
          }
        }
        Cookies.remove(authorizedKey)
        localStorage.removeItem('pcType')
        localStorage.removeItem(userKey)
        // 清空测评缓存的用户信息
        localStorage.removeItem('$user')
        window.$app.user = null
        // 删除测评缓存已被清除的标志位本身
        // cookie.delete('ai_exam_cache_cleared')
        if (window.$app.logoffApi && window.$app.appType === 'web') {
          axios.post(window.$app.logoffApi)
            .then(resp => {
              if (resp.data && resp.data.responseEntity) {
                window.location.href = resp.data.responseEntity
              } else {
                handleLogoOut()
              }
            })
            .catch(err => {
              handleLogoOut()
              console.log(err)
            })
        } else {
          handleLogoOut()
        }
      },

      getLocalAuth() {
        const token = $ui.local.get('token')
        const tokenExpired = $ui.local.get('token_expired')
        const user = $ui.local.get('user')
        const now = Date.now()
    
        if (token && tokenExpired && tokenExpired > now) {
          this.saveLocalAuth({ token, tokenExpired, user })
        } else {
          router.replace('/login')
        }
      },
    
      saveLocalAuth(params) {
        let { token, tokenExpired, user } = params
    
        if (token) {
          $ui.local.set('token', token)
          $app.token = token
        }
    
        if (tokenExpired) {
          $ui.local.set('token_expired', tokenExpired)
          $app.tokenExpired = tokenExpired
        }
    
    
        if (user) {
          user = Object.assign({}, user)
          $ui.local.set('user', user)
          $app.user = user
          if (user.roles) {
            $app.user.roleIdList = user.roles.map(item => item.roleKey)
          }
        }
      },
    
      logoff() {
        $ui.local.remove('token')
        $ui.local.remove('token_expired')
        $ui.local.remove('user')
        router.replace('/login')
      }
    })

    Object.assign(window.$app, config)

    Object.defineProperties(window.$app, {
      authorized: {
        enumerable: true,
        get () {
          return !!Cookies.get(authorizedKey) && !!localStorage.getItem(userKey)
        }
      }
    })

    window.$app.title = { text: '' }
    reactive(window.$app)
    reactive(window.$app.title)
    window.$app.user = new User()

    if (window.$app.authorized) {
      Object.assign(window.$app.user, JSON.parse(localStorage.getItem(userKey)))
    }

    app.use(TwFrontLog)
    app.use(UiUtils, { ...window.$ui, wait: 3000 })
    app.config.globalProperties.$app = window.$app

  }
}
